package com.aaa.book_mall.controller;

import com.aaa.book_mall.dao.*;
import com.aaa.book_mall.dao.impl.*;
import com.aaa.book_mall.entity.*;
import com.aaa.book_mall.util.LayTab;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import com.aaa.book_mall.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 审核记录操作
 * @ClassName: AuditController
 * @Author: fengyun
 * @Date: 2021/1/21 9:35
 * @Version: 1.0
 */
@RestController
@RequestMapping("/audit")
public class AuditController {
    @Autowired
    private OutDao outDaoimpl;

    @Autowired
    private OutAuditDao outAuditDaoimpl;

    private BookDao bookDao = new BookDaoImpl();
    private AuditDao auditDao = new AuditDaoImpl();
    private RecordDao recordDao = new RecordDaoImpl();
    private RequestDao requestDao = new RequestDaoImpl();
    private RejectDao rejectDao = new RejectDaoImpl();
    private DetailDao detailDao = new DetailDaoImpl();

    /* *
     *  审核不同意的方法
     * @param outs
     * @param request
     * @return java.util.Map
     * @date 2021/1/21 11:45
     */
    @RequestMapping("/Outdisagree")
    public Map agree(String disagree, String applyData, HttpServletRequest request) {
        //将json字符串风装称实体对象
        Out out=null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            out = mapper.readValue(applyData, Out.class);
            System.out.println(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        不同意的状态值
        String status="2";
//        1、更改t_out表中的状态
        int statusV = outDaoimpl.updateStatus(status, out.getOutnumber());
//        2、写入到t_audit表
        //      通过session获取登录人的信息，用以生成outnumber
        HttpSession session = request.getSession();
        Staff staff =(Staff) session.getAttribute("staff");
//      获取session中的员工编号
        int staffId=staff.getStaffId();
//        获取session中的员工姓名
        String staffname = staff.getStaffName();
        System.out.println("disagree:审核人员的staffId"+staffId);
//        获取现在的时间，和用户便函共同组成outnumber
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        String format = simpleDateFormat.format(date);
        String stringDate =staffId+format.replace("-", "").replace(":","");

        OutAudit outAudit = new OutAudit(null, stringDate, staffId, staffname, out.getOutnumber(), "不同意",disagree, date);
        int i = outAuditDaoimpl.insertInfo(outAudit);

        HashMap<Object, Object> map = new HashMap<>();
        if(i>0){
            map.put("code","1");
            map.put("msg","操作成功");
        }else{
            map.put("code","0");
            map.put("msg","操作失败");
        }
        return map;
    }

    /**
     * 审核不同意的方法
     * 向申请记录表添加数据
     */
    @RequestMapping("/disagree")
//@RequestBody Request requestDate,
    public Map disagree( String disagree, String applyData, HttpServletRequest request1) {
        System.out.println("不同意");
        //将json字符串风装称实体对象
        Request request = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            request = mapper.readValue(applyData,Request.class );
            System.out.println("将json字符串风装称实体对象"+request);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        不同意的状态值
        String status="2";
//        1、更改t_out表中的状态
        assert request != null;
        int statusV = requestDao.updateStatus(request.getNumber(),status);
        System.out.println("修改状态："+statusV);
//        2、写入到t_audit表
        //      通过session获取登录人的信息，用以生成outnumber
        HttpSession session = request1.getSession();
        Staff staff =(Staff) session.getAttribute("staff");
////      获取session中的员工编号
        Integer staffId = staff.getStaffId();
        //Object staffid = session.getAttribute("staffid");
        //int staffId=Integer.parseInt(staffid+"");

        //        获取session中的员工姓名
        String staffname = staff.getStaffName();
        //System.out.println("disagree:审核人员的staffId"+staffId);
//        获取现在的时间，和用户便函共同组成outnumber
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        String format = simpleDateFormat.format(date);
        String stringDate =staffId+format.replace("-", "").replace(":","");

        //向驳回表添加数据
        Reject reject = new Reject(null, request.getNumber(),staffId, staffname, request.getBookcount(), request.getBookprice(), date, "2");
        int i1 = rejectDao.insertReject(reject);
        System.out.println("添加成功"+i1);

        System.out.println(reject);
        Audit audit = new Audit(null, stringDate, staffId, staffname, request.getNumber(), "不同意",disagree, date);
        int i = auditDao.insertAudit(audit);

        HashMap<Object, Object> map = new HashMap<>();
        if(i>0){
            map.put("code","1");
            map.put("msg","操作成功");
        }else{
            map.put("code","0");
            map.put("msg","操作失败");
        }
        return map;
    }

    /* *
     *  查询审核记录
     * @param outAudit
     * @return com.aaa.book_mall.util.LayTab
     * @date 2021/1/21 16:55
     */
    @RequestMapping("/allAudit")
    public LayTab queryAllOut(OutAudit outAudit){
        System.out.println(outAudit);
//        分页查询
        List<Map<String, Object>> maps = outAuditDaoimpl.selectAllAudit(outAudit);
        int countAudit = outAuditDaoimpl.countAudit();
        LayTab layTab = new LayTab(countAudit, maps);
        return layTab;
    }

    /**
     * 查询审核记录
     */
    @RequestMapping("/AllAudit")
    public LayTab queryAll(Audit audit){
        System.out.println(audit);
//        分页查询
        List<Map<String, Object>> maps = auditDao.selectAllAudit(audit);
        int countAudit = auditDao.countAudit();
        LayTab layTab = new LayTab(countAudit, maps);
        return layTab;
    }

    /**
     * 根据id查询audit_number
     */
    @RequestMapping("/getOneAudit")
    public String getOneAudit(Integer id){
        System.out.println("开始查询audit_number");
        String oneAudit = auditDao.getOneAudit(id);
        return oneAudit;
    }


    /**
     * 删除
     * @param req
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/deleteAudit")
    public Map deleteAudit(HttpServletRequest req) throws ServletException, IOException {
        //获取id
        String id = req.getParameter("audit_id");
        int i = auditDao.deleteAudit(Integer.parseInt(id));
        HashMap<Object, Object> map = new HashMap<>();
        if(i>0){
            map.put("code","1");
            map.put("msg","添加成功");
        }else{
            map.put("code","0");
            map.put("msg","添加失败");
        }

     /*   Result result;
        //判断删除是否成功
        if(i>0){
            result = new Result("1","删除成功");
        }else {
            result = new Result("0", "删除失败");
        }
        //将其转成json格式
        String s = JSON.toJSONString(result);
        resp.getWriter().write(s);*/
     return map;
    }

    @RequestMapping("/add")
    public Map add(Request outs, HttpServletRequest request) {
        System.out.println("添加入库进来了");
        System.out.println(outs);
        //        获取现在的时间，和用户便函共同组成outnumber
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        String format = simpleDateFormat.format(date);
        String stringDate = 109 + format.replace("-", "").replace(":", "");
        System.out.println("outnumber" + stringDate);

        System.out.println("入库状态:");
               //2、更改t_book对应书本的数量
         //            先根据outnumber到t_outdetail表中查询申请的每一本书
          //            根据查询出来的书的量和书的编号到t_book表中操作
          //
        List<Detail> outDetails = detailDao.queryDetail(outs.getNumber());//查询订单详情
        if(outDetails!=null && outDetails.size()>0){
            for (Detail outDetail : outDetails) {
                int bookcount = bookDao.selectCountByBookid(outDetail.getBookid());//查询t_book中的书本数量
                // double price = bookDao.selectPriceByBookid(outDetail.getBookid());//查询t_book中的书本进价
                //bookcount=bookcount+outDetail.getBookcount();//将原有数量加上申请的数量
                bookDao.updateCountByBookid(bookcount,outDetail.getBookid());//更新t_book中的count
            }
        }
        //Record record = new Record(null,outs.getNumber(),109,"小蓝",outs.getBookcount(),outs.getBookprice(),date);
        //int i1 = recordDao.insertRecord(record);
        HashMap<Object, Object> map = new HashMap<>();
        int i=1;
        if(i>0){
            map.put("code","1");
            map.put("msg","添加成功");
        }else{
            map.put("code","0");
            map.put("msg","添加失败");
        }

        return map;

    }

    }
